package com.example.managemyself.ui.profile;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;

import com.example.managemyself.R;
import com.example.managemyself.data.model.User;
import com.example.managemyself.model.UserSettings;
import com.example.managemyself.ui.auth.LoginActivity;
import com.example.managemyself.ui.profile.EditProfileActivity;
import com.example.managemyself.util.SettingsManager;
import com.example.managemyself.util.UserManager;
import com.example.managemyself.viewmodel.ProfileViewModel;

public class ProfileFragment extends Fragment {

    private ProfileViewModel viewModel;
    private TextView tvUsername;
    private Button btnEditProfile;
    private Button btnSettings;
    private Button btnLogout;
    private Button btnAbout;

    public ProfileFragment() {
        // 必须有一个空的公共构造函数
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_profile, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        try {
            // 初始化视图
            tvUsername = view.findViewById(R.id.tv_username);
            btnEditProfile = view.findViewById(R.id.btn_edit_profile);
            btnSettings = view.findViewById(R.id.btnSettings);
            btnLogout = view.findViewById(R.id.btn_logout);
            btnAbout = view.findViewById(R.id.btnAbout);

            // 初始化ViewModel
            viewModel = new ViewModelProvider(this).get(ProfileViewModel.class);

            // 设置当前用户信息
            User currentUser = UserManager.getInstance().getCurrentUser();
            if (currentUser != null) {
                tvUsername.setText(currentUser.getUsername());
            } else {
                tvUsername.setText("未登录用户");
            }

            // 设置按钮点击事件
            if (btnEditProfile != null) {
                btnEditProfile.setOnClickListener(v -> editProfile());
            }
            if (btnSettings != null) {
                btnSettings.setOnClickListener(v -> openSettings());
            }
            if (btnLogout != null) {
                btnLogout.setOnClickListener(v -> confirmLogout());
            }
            if (btnAbout != null) {
                btnAbout.setOnClickListener(v -> showAboutDialog());
            }

            // 简化用户设置加载
            if (currentUser != null) {
                try {
                    viewModel.getUserSettings(currentUser.getId()).observe(getViewLifecycleOwner(), this::updateSettingsUI);
                } catch (Exception e) {
                    // 如果加载用户设置失败，忽略错误
                }
            }
        } catch (Exception e) {
            Toast.makeText(requireContext(), "页面初始化失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 更新设置UI
     */
    private void updateSettingsUI(UserSettings settings) {
        // 根据设置更新UI
        if (settings != null) {
            // 可以根据需要更新UI
        }
    }

    /**
     * 编辑个人资料
     */
    private void editProfile() {
        Intent intent = new Intent(getActivity(), EditProfileActivity.class);
        startActivity(intent);
    }

    /**
     * 打开设置
     */
    private void openSettings() {
        // 导航到设置页面
        Navigation.findNavController(requireView()).navigate(R.id.action_profileFragment_to_settingsFragment);
    }

    /**
     * 确认登出
     */
    private void confirmLogout() {
        new AlertDialog.Builder(requireContext())
                .setTitle("确认登出")
                .setMessage("您确定要登出吗？")
                .setPositiveButton("确定", (dialog, which) -> logout())
                .setNegativeButton("取消", null)
                .show();
    }

    /**
     * 登出
     */
    private void logout() {
        UserManager.getInstance().logout(requireContext(), new UserManager.SimpleCallback() {
            @Override
            public void onSuccess() {
                // 跳转到登录界面
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
                if (getActivity() != null) {
                    getActivity().finish();
                }
            }

            @Override
            public void onError(String error) {
                Toast.makeText(getContext(), "登出失败: " + error, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 显示关于对话框
     */
    private void showAboutDialog() {
        new AlertDialog.Builder(requireContext())
                .setTitle("关于")
                .setMessage("ManageMyself v1.0\n\n一个帮助您管理生活和工作的个人管理应用。\n\n© 2023 ManageMyself Team")
                .setPositiveButton("确定", null)
                .show();
    }
}
